package com.bawei.module_goods.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.bawei.module_goods.intent.ShoppingCartIntent
import com.bawei.module_goods.repository.ShoppingCartRepository
import com.bawei.module_goods.state.ShoppingCartState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch

class ShoppingCartViewModel : ViewModel() {
    private val repository = ShoppingCartRepository()
    private val _state = MutableStateFlow<ShoppingCartState>(ShoppingCartState.Init)
    val state: StateFlow<ShoppingCartState> = _state

    fun dispatch(intent: ShoppingCartIntent) {
        when (intent) {
            is ShoppingCartIntent.LoadCartList -> loadCartList()
            is ShoppingCartIntent.UpdateCartItem -> updateCartItem(intent.cartId, intent.number)
        }
    }

    private fun loadCartList() {
        _state.value = ShoppingCartState.Loading
        viewModelScope.launch {
            try {
                val items = repository.getCartDisplayList()
                _state.value = ShoppingCartState.Success(items)
            } catch (e: Exception) {
                _state.value = ShoppingCartState.Error(e.message ?: "未知错误")
            }
        }
    }

    private fun updateCartItem(cartId: Int, number: Int) {
        android.util.Log.d("CartLog", "ViewModel updateCartItem cartId=$cartId, number=$number")
        viewModelScope.launch {
            try {
                val success = repository.updateCartItem(cartId, number)
                android.util.Log.d("CartLog", "ViewModel updateCartItem result=$success")
                if (success) {
                    loadCartList() // 更新成功后刷新
                }
            } catch (e: Exception) {
                android.util.Log.e("CartLog", "ViewModel updateCartItem error: ${e.message}")
            }
        }
    }
} 